package Netty.BIO;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 多线程阻塞Socket服务
 * 每一个连接都会分配一个线程
 * 当有大量连接的时候会导致oom
 *
 * @author hecai
 * @date 2021/11/7
 */
public class MultiThreadBlockSocketServer {
    public static void main(String[] args) throws IOException {
        // 创建server 9090
        ServerSocket serverSocket = new ServerSocket(9090);
        while (true) {
            System.out.println("等待连接。。。。");
            // 等待连接
            Socket accept = serverSocket.accept();
            System.out.println("连接成功....");
            // 伪异步阻塞IO 将下面线程丢到线程池中
            new Thread(() -> {
                try {
                    handler(accept);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static void handler(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("准备read ...");
        // 接受客户端的数据，阻塞方法，没有数据时就阻塞
        int read = clientSocket.getInputStream().read(bytes);
        System.out.println("read准备结束....");
        // 如果读到数据
        if (read != -1) {
            System.out.println("收到数据内容：" + new String(bytes, 0, read, "GBK"));
        }

    }
}
